package com.demo.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;


public class ExcelUtil {
	public static ExcelData getExcelData(InputStream is) {
		if (is == null) {
			return null;
		}
		List<String> columnNameList = new ArrayList<String>();
		List<Map<String, String>> columnValueList = new ArrayList<Map<String, String>>();
		ExcelData excelData = new ExcelData(columnNameList, columnValueList);

		try {
			// 得到Excel工作簿对象
			HSSFWorkbook wb = new HSSFWorkbook(is);
			// 得到Excel工作表对象
			HSSFSheet sheet = wb.getSheetAt(0);
			int firstRowNum = sheet.getFirstRowNum();
			int lastRowNum = sheet.getLastRowNum();
			// 得到Excel工作表的行
			HSSFRow row = sheet.getRow(firstRowNum);
			short firstCellNum = row.getFirstCellNum();
			short lastCellNum = row.getLastCellNum();
			for (int i = 0 + firstCellNum; i < lastCellNum + 0; i++) {
				HSSFCell cell = row.getCell(i);
				columnNameList.add(getCellValueAsString(cell));
			}
			for (int j = 1 + firstRowNum; j <= lastRowNum + 0; j++) {
				HSSFRow row_j = sheet.getRow(j);
				HashMap<String, String> row_map = new HashMap<String, String>();
				for (int i = 0 + firstCellNum; i < lastCellNum + 0; i++) {
					HSSFCell cell = row_j.getCell(i);
					row_map.put(columnNameList.get(i), getCellValueAsString(cell));
				}
				columnValueList.add(row_map);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return excelData;
	}

	private static String getCellValueAsString(HSSFCell cell) {
		if (cell == null) {
			return "";
		} else {
			switch (cell.getCellType()) {
			case Cell.CELL_TYPE_BLANK:
			case Cell.CELL_TYPE_ERROR:
				return "";
			case Cell.CELL_TYPE_BOOLEAN:
				return "" + (cell.getBooleanCellValue() ? "true" : "false");
			case Cell.CELL_TYPE_NUMERIC:
				return ("" + cell.getNumericCellValue()).replaceAll(".0+$", "");
			default:
				return cell.getStringCellValue().trim();
			}
		}
	}

}
